import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '@/views/MyLayout.vue'
// import WheatPage from '@/views/WheatPage.vue'
// import BuckWheatPage from '@/views/BuckWheatPage.vue'
// import CornPage from '@/views/CornPage.vue'
// import MilletPage from '@/views/MilletPage.vue'
// import SorghumPage from '@/views/SorghumPage.vue'
// import SoybeanPage from '@/views/SoybeanPage.vue'
// import PaddyPage from '@/views/PaddyPage.vue'
import MyTest from '@/views/MyTest.vue'
import GrainDetails from '@/views/GrainDetails.vue'
Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/home' },
  { path: '/home', component: Layout },
  // { path: '/wheat', component: WheatPage },
  // { path: '/buckwheat', component: BuckWheatPage },
  // { path: '/corn', component: CornPage },
  // { path: '/millet', component: MilletPage },
  // { path: '/sorghum', component: SorghumPage },
  // { path: '/soybean', component: SoybeanPage },
  // { path: '/paddy', component: PaddyPage },
  { path: '/test', component: MyTest },
  { path: '/grain', component: GrainDetails }
]

const router = new VueRouter({
  routes
})

router.beforeEach((to, from, next) => {
  // 检查路由是否存在
  if (router.getRoutes().some(route => route.path === to.path)) {
    next() // 如果存在，则继续导航
  } else {
    // 动态加载组件
    const routePath = to.path
    import(`@/views${routePath.charAt(0).toUpperCase() + routePath.slice(1)}Page.vue`).then(module => {
      router.addRoute({
        path: routePath,
        component: module.default
      })
      next({ ...to, replace: true })
    }).catch(() => {
      next('/home') // 如果组件未找到，重定向到主页
    })
  }
})

export default router
